package com.manong.bookstore.user.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Map;

import com.manong.bookstore.user.feign.ShoppingcartFeignService;
import com.manong.bookstore.user.feign.UserFeignService;
import com.manong.bookstore.user.util.CookieFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.manong.bookstore.user.entity.UserEntity;
import com.manong.bookstore.user.service.UserService;
import com.manong.common.utils.PageUtils;
import com.manong.common.utils.R;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @author cyq
 * @email 465447222@qq.com
 * @date 2021-01-27 21:34:32
 */
@RestController
@RequestMapping("user/user")
public class UserController {
//	@Value("${userPassword}")
//	private String userPassword;

	@Autowired
	private UserService userService;
	@Autowired
	private UserFeignService userFeignService;
	@Autowired
	private ShoppingcartFeignService shoppingcartFeignService;

//	@Resource(name = "addToShoppingcartSession")
//	private AddToShoppingcartSession addToShoppingcartSession;

	/**
	 * 测试session，添加数据
	 */
	@RequestMapping("/testSet")
	@ResponseBody
	public R testSet(@RequestParam Map<String, Object> params, HttpSession session) {
		Object msg = params.get("msg");

		System.out.println(session.getId() + " set " + msg);
		session.setAttribute("msg", msg);

		return R.ok();
	}

	/**
	 * 测试session，获取数据
	 */
	@RequestMapping("/testGet")
	@ResponseBody
	public R testGet(@RequestParam Map<String, Object> params, HttpSession session) {
		System.out.println(session.getId() + " get " + session.getAttribute("msg"));

		return R.ok();
	}

	/**
	 * 列表
	 * 查询所有
	 */
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = userService.queryPage(params);

		return R.ok().put("page", page);
	}


	/**
	 * 信息
	 * 查询某个用户，参数为userId
	 * 【【！！！返回值带密码，要注意！！！】】
	 */
	@RequestMapping("/info")
	public R info(@RequestParam Map<String, Object> params) {
		UserEntity user = userService.getById(params.get("userId").toString());

//		密码置空，防止信息泄露
//		user.setPassword(null);

		return R.ok().put("user", user);
	}

	/**
	 * 信息
	 * 查询某个用户的简单信息，参数为userId
	 * 返回简单信息
	 */
	@RequestMapping("/sampleInfo/{userId}")
	public R sampleInfo(@PathVariable("userId") Integer userId) {
		UserEntity user = userService.getById(userId);

		user.setUserType(null);
		user.setPoints(null);
		user.setPhoneNumber(null);
		user.setEmail(null);
		user.setPassword(null);

		return R.ok().put("user", user);
	}


	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public R save(@RequestBody UserEntity user) {
		System.out.println("save: " + user);

		userService.save(user);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	public R update(@RequestBody UserEntity user) {
		userService.updateById(user);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	public R delete(@RequestBody Integer[] userIds) {
		userService.removeByIds(Arrays.asList(userIds));

		return R.ok();
	}



	/**(2020-09-06)
	 * 注册
	 * user
	 */
	@RequestMapping("/register")
	public R register(@RequestBody UserEntity user) {
		System.out.println("register: " + user);

		Integer userId = userService.register(user);

		if (userId == -1) {
			return R.ok().put("status", "error").put("message", "用户名重复");
		} else if (userId == -2) {
			return R.ok().put("status", "error").put("message", "手机号码重复");
		} else {
			return R.ok().put("status", "ok").put("message", userId);
		}
	}

	/**(2020-09-06)
	 * 使用用户名或者手机号登录
	 * ID(用户名或者手机号), password
	 */
	@RequestMapping("/login")
	public R login(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		Object ID = params.get("ID");
		Object password = params.get("password");
		String[] checkColumns = {"user_name", "phone_number"};// 根据 用户名 或者 手机号 登陆

		System.out.println("login: " + ID + " " + password);

		if(ID == null || password == null)
			return R.ok().put("status", "error: miss parameter");


		for(String checkColumn : checkColumns) {
			UserEntity user = userService.login(ID.toString(), password.toString(), checkColumn);

			// 登录成功
			if(user != null) {
				Cookie cookie = CookieFinder.findCookie(request, "USERSESSION");
				boolean flag = false;

				////// 额外部分 //////
				session.setAttribute("userId", user.getUserId());


				//为空，首次访问，需要新建
				//不为空，但是找不到（已过期），需要新建
				//更换账号登录，需要重写userId
				if(cookie == null || !userFeignService.search(cookie.getValue())) {
					flag = true;
				}
				else {
					userFeignService.setAttribute(cookie.getValue(), "userId", user.getUserId().toString());
					userFeignService.setAttribute(cookie.getValue(), "userName", user.getUserName());
					////// 额外部分 //////
					//addToShoppingcartSession.addRequest(shoppingcartFeignService, session, user.getUserId());
				}

				if(flag) {
					String sessionId = userFeignService.create();
					userFeignService.setAttribute(sessionId, "userId", user.getUserId().toString());
					userFeignService.setAttribute(sessionId, "userName", user.getUserName());
					////// 额外部分 //////
					//addToShoppingcartSession.addRequest(shoppingcartFeignService, session, user.getUserId());

					cookie = new Cookie("USERSESSION", sessionId);
					cookie.setPath("/");
					cookie.setHttpOnly(true);
					response.addCookie(cookie);

					System.out.println("new session: " + sessionId);
				}

				return R.ok().put("status", "ok").put("userId", user.getUserId());
			}
		}

		return R.ok().put("status", "error: not match");
	}

	/**(2020-09-06)
	 * 使用userId登录（只检查userId和密码是否匹配）
	 * userId, password
	 */
	@RequestMapping("/loginByUserId")
	public R loginByUserId(@RequestParam Map<String, Object> params) {
		Object userId = params.get("userId");
		Object password = params.get("password");

		System.out.println("loginById: " + userId + " " + password);

		if(userId == null || password == null)
			return R.ok().put("status", "error: miss parameter");


		// 检查使用用户ID登录
		UserEntity result = userService.login(userId.toString(), password.toString(), "user_id");

		if(result != null)
			return R.ok().put("status", "ok").put("userId", result);

		return R.ok().put("status", "error: not match");
	}

	/**(2020-09-06)
	 * 修改用户信息（只能修改邮箱、密码）
	 * userId, name, value
	 */
	@RequestMapping("/update/info")
	public R updateInfo(@RequestParam Map<String, Object> params) {
		Object userId = params.get("userId");
		Object name = params.get("name");
		Object value = params.get("value");

		System.out.println("updateInfo: " + userId + " " + name + " " + value);

		if (userId == null || name == null || value == null)
			return R.ok().put("status", "error: miss parameter");

		boolean status = userService.updateInfo(userId.toString(), name.toString(), value.toString());

		return status ? R.ok().put("status", "ok") : R.ok().put("status", "error: incorrect userId");
	}


	/**
	 * 增加用户积分
	 * userId, points
	 */
	@RequestMapping("/update/points/add")
	public R addPoint(@RequestParam Map<String, Object> params) {
		Integer userId = (Integer) params.get("userId");
		BigDecimal points = (BigDecimal) params.get("points");

		userService.addPoint(userId, points);

		// 获取修改后的积分数
		UserEntity user = userService.getById(userId);

		return R.ok().put("points", user.getPoints());
	}

	/**
	 * 减少用户积分
	 * userId, points
	 */
	@RequestMapping("/update/points/del")
	public R delPoint(@RequestParam Map<String, Object> params) {
		Integer userId = (Integer) params.get("userId");
		BigDecimal points = (BigDecimal) params.get("points");

		userService.delPoint(userId, points);

		// 获取修改后的积分数
		UserEntity user = userService.getById(userId);

		return R.ok().put("points", user.getPoints());
	}
}
